<?php
/**
 * 卖家活动管理
 *
 *
 *
 *
 * @copyright  Copyright (c) 中国追溯
 * @since      File available since Release v1.1
 */
use Shopnc\Tpl;


defined('InShopNC') or exit('Access Invalid!');
class store_marketing_activityControl extends BaseSellerControl {
    public function __construct() {
        parent::__construct();
        Language::read('member_store_index');
    }

    public function indexOp() {
        $this->store_marketing_activityOp();
    }

    /**
     * 活动管理
     */
    public function store_marketing_activityOp() {
        $marketing_activity   = Model('marketing_activity');
        //活动为商品活动，并且为开启状态
        $list   = $marketing_activity->getList(array('store_marketing_activity'=>true), '*', 0, $_REQUEST['rp'], 'marketing_activity.marketing_activity_sort asc');
        //获取该商户是否报名该活动
        $list = $marketing_activity->checkMerchantApply($_SESSION['store_id'], $list);

        //拼接详情页地址
        $details_site = [
            3 => 'index.php?act=store_promotion_kanjia&op=kanjia_manage_apply&marketing_activity_id=',
            4 => 'index.php?act=store_promotion_pintuan&op=pintuan_manage_apply&marketing_activity_id=',
            'default' => 'index.php?act=store_marketing_activity&op=activity_apply&marketing_activity_id='
        ];
        array_walk($list, function(&$item, $key) use($details_site) {
            $marketing_activity_type = isset($item['marketing_activity_type']) ? (int)$item['marketing_activity_type'] : 0;
            $item['details_url'] = isset($details_site[$marketing_activity_type]) ? $details_site[$marketing_activity_type] : $details_site['default'];
            $item['details_url'] .= $item['marketing_activity_id'];
        });
        /**
         * 页面输出
         */
        Tpl::output('list',$list);
        Tpl::output('show_page', $marketing_activity->showpage(2));
        self::profile_menu('store_marketing_activity');
        Tpl::showpage('store_marketing_activity.list');
    }

    /**
     * 参与隐藏活动
     */
    public function apply_activity_hideOp()
    {
        $marketing_activity_model = Model('marketing_activity');
        //根据活动编号查询活动信息
        $marketing_activity_id = (string)$_GET['marketing_activity_id'];
        //解密 marketing_activity_id 参数
        $marketing_activity_id = $marketing_activity_model->decryptActivityApplyId($marketing_activity_id);
        if(empty($marketing_activity_id)) {
            showMessage(Language::get('para_error'),'index.php?act=store_marketing_activity&op=store_marketing_activity','html','error');
        }

        $map = array(
            'marketing_activity.marketing_activity_id' => $marketing_activity_id,
            'marketing_activity.marketing_activity_state' => $marketing_activity_model::ACTIVITY_OPEN
        );
        $activity_info  = $marketing_activity_model->getOneData($map);
        //活动类型必须是商品并且活动没有关闭并且活动进行中
        if(empty($activity_info) || $activity_info['marketing_activity_state'] != $marketing_activity_model::ACTIVITY_OPEN || $activity_info['marketing_activity_end_date'] < TIMESTAMP){
            showMessage(Language::get('store_activity_not_exists'),'index.php?act=store_marketing_activity&op=store_marketing_activity','html','error');
        }
        Tpl::output('activity_info',$activity_info);

        //查询商品分类列表
        $gc = Model('goods_class');
        $gc_list    = $gc->getTreeClassList(3);
        foreach($gc_list as $k=>$gc){
            $gc_list[$k]['gc_name'] = '';
            $gc_list[$k]['gc_name'] = str_repeat("&nbsp;",$gc['deep']*2).$gc['gc_name'];
        }
        Tpl::output('gc_list',$gc_list);
        //查询品牌列表
        $brand  = Model('brand');
        $brand_list = $brand->getBrandList(array());
        Tpl::output('brand_list',$brand_list);

        //确定操作对象
        $model_name = $marketing_activity_model->activityTypeShiftModel($activity_info['marketing_activity_type']);
        if (!$model_name) {
            return array();  //营销类型错误
        }
        $model_name = Model($model_name);
        $map = array(
            'marketing_activity_id' => $marketing_activity_id,
            'store_id'  => $_SESSION['store_id']
        );
        $activity_goods = $model_name->getActivityGoodsList($map);

        //是否显示报名
        $store_goods_limit = isset($activity_info['store_goods_limit']) ? (int)$activity_info['store_goods_limit'] : 0;     //活动商家报名限制
        $already_apply = $model_name->getActivityApplyGoodsCount($marketing_activity_id, $_SESSION['store_id']);    //商家已经报名该营销活动商品数量
        $if_show_apply = ($store_goods_limit > $already_apply) ? ($store_goods_limit - $already_apply) : false;     //若显示，返回剩余额度，否则返回false
        Tpl::output('if_show_apply', $if_show_apply);
        Tpl::output('marketing_activity_id', $marketing_activity_id);
        Tpl::output('activity_goods', $activity_goods);

        /**
         * 页面输出
         */
        self::profile_menu('activity_apply');
        Tpl::showpage('store_marketing_activity.apply');
    }


    /**
     * 参与活动
     */
    public function activity_applyOp(){
        //根据活动编号查询活动信息
        $marketing_activity_id = intval($_GET['marketing_activity_id']);
        if($marketing_activity_id <= 0){
            showMessage(Language::get('para_error'),'index.php?act=store_marketing_activity&op=store_marketing_activity','html','error');
        }
        $marketing_activity_model = Model('marketing_activity');
        $map = array(
            'marketing_activity.marketing_activity_id' => $marketing_activity_id,
            'marketing_activity.marketing_activity_state' => $marketing_activity_model::ACTIVITY_OPEN,
            'marketing_activity.marketing_activity_show' => $marketing_activity_model::ACTIVITY_SHOW
        );
        $activity_info  = $marketing_activity_model->getOneData($map);
        //活动类型必须是商品并且活动没有关闭并且活动进行中
        if(empty($activity_info) || $activity_info['marketing_activity_state'] != $marketing_activity_model::ACTIVITY_OPEN || $activity_info['marketing_activity_end_date'] < TIMESTAMP){
            showMessage(Language::get('store_activity_not_exists'),'index.php?act=store_marketing_activity&op=store_marketing_activity','html','error');
        }
        Tpl::output('activity_info', $activity_info);

        //查询商品分类列表
        $gc = Model('goods_class');
        $gc_list    = $gc->getTreeClassList(3);
        foreach($gc_list as $k=>$gc){
            $gc_list[$k]['gc_name'] = '';
            $gc_list[$k]['gc_name'] = str_repeat("&nbsp;",$gc['deep']*2).$gc['gc_name'];
        }
        Tpl::output('gc_list',$gc_list);
        //查询品牌列表
        $brand  = Model('brand');
        $brand_list = $brand->getBrandList(array());
        Tpl::output('brand_list',$brand_list);

        //确定操作对象
        $model_name = $marketing_activity_model->activityTypeShiftModel($activity_info['marketing_activity_type']);
        if (!$model_name) {
            return array();  //营销类型错误
        }
        $model_name = Model($model_name);
        $map = array(
            'marketing_activity_id' => $marketing_activity_id,
            'store_id'  => $_SESSION['store_id']
        );
        $activity_goods = $model_name->getActivityGoodsList($map);

        //是否显示报名
        $store_goods_limit = isset($activity_info['store_goods_limit']) ? (int)$activity_info['store_goods_limit'] : 0;     //活动商家报名限制
        $already_apply = $model_name->getActivityApplyGoodsCount($marketing_activity_id, $_SESSION['store_id']);    //商家已经报名该营销活动商品数量
        $if_show_apply = ($store_goods_limit > $already_apply) ? ($store_goods_limit - $already_apply) : false;     //若显示，返回剩余额度，否则返回false
        Tpl::output('if_show_apply', $if_show_apply);
        Tpl::output('activity_goods', $activity_goods);
        Tpl::output('marketing_activity_id', $marketing_activity_id);

        /**
         * 页面输出
         */
        self::profile_menu('activity_apply');
        Tpl::showpage('store_marketing_activity.apply');
    }

    /**
     * 选择活动商品
     **/
    public function goods_selectOp()
    {
        $condition = array(
            'store_id' => $_SESSION['store_id']
        );
        if (isset($_GET['goods_name']) && !empty($_GET['goods_name'])) $condition['goods_name'] = array('like', '%'.$_GET['goods_name'].'%');

        //获取商品
        $model_goods = Model('goods');
        $goods_list = $model_goods->getGeneralGoodsOnlineList($condition, '*', 10);

        //处理商品
        $model_activity = Model('marketing_activity');
        $marketing_activity_id = (int)$_GET['marketing_activity_id'];
        $goods_list = $model_activity->disposeStoreGoodsSelect($marketing_activity_id, $goods_list);
        $marketing_activity_data = $model_activity->getOneById($marketing_activity_id);
//        dump($goods_list);die;
        Tpl::output('goods_list', $goods_list);
        Tpl::output('show_page', $model_goods->showpage());
        Tpl::output('marketing_activity_id', $marketing_activity_id);
        Tpl::output('marketing_activity_type', $marketing_activity_data['marketing_activity_type']);
        Tpl::showpage('store_marketing_activity.goods', 'null_layout');
    }

    /**
     * 活动申请保存
     */
    public function activity_apply_saveOp()
    {
        $marketing_activity_id = isset($_POST['marketing_activity_id']) ? (int)$_POST['marketing_activity_id'] : 0;
        $model_activity = Model('marketing_activity');
        //获得营销活动数据
        $field = '*';
        $activity_data = $model_activity->getActivityOpenDetails($marketing_activity_id, $field);  
        if (empty($activity_data)) {
            showDialog('不存在该开启的活动', 'index.php?act=store_marketing_activity&op=index');
        }

        //确定操作对象
        $model_name = $model_activity->activityTypeShiftModel($activity_data['marketing_activity_type']);
        if (!$model_name) {
            showDialog('错误的营销类型', 'index.php?act=store_marketing_activity&op=index');
        }
        $model_name = Model($model_name);

        $add_data = isset($_POST['add_data']) ? (array)$_POST['add_data'] : array();
        foreach ($add_data as $goods_id => $item) {
            if (!isset($item['goods_id'])) unset($add_data[$goods_id]); //删除错误的数据
        }
        //判断页面参数
        if(empty($add_data)){
            showDialog('请选择你要操作的对象', 'index.php?act=store_marketing_activity&op=index');
        }

        //添加数据
        try {
            //打开事务
            $model_name->beginTransaction();
            foreach ($add_data as $goods_id => $item) {
                $transfer_data = array(
                    'marketing_activity_id' => $marketing_activity_id,
                    'goods_id' => $item['goods_id'],
                    'promotion_price' => $item['promotion_price'],
                    'upper_limit' => $item['upper_limit'],
                    'admin_apply' => 0,
                    'apply_user_id' => $_SESSION['member_id'],
                    'apply_user_name' => $_SESSION['member_name']
                );
                $add_state = $model_name->addActivityGoodsData($transfer_data);
                if (!$add_state) {
                    throw new Exception($model_name->getErrorInfo());
                }
            }
            //提交事务
            $model_name->commit();
        } catch (Exception $e) {
            //回滚事务
            $model_name->rollback();
            showDialog($e->getMessage(), 'index.php?act=store_marketing_activity&op=index');
        }

        showDialog(Language::get('store_activity_submitted'),'reload','succ');
    }

    /**
     * 获取营销活动详情
     * @return html
     */
    public function get_activity_detailsOp()
    {
        $marketing_activity_id = isset($_GET['marketing_activity_id']) ? (int)$_GET['marketing_activity_id'] : 0;
        $marketing_activity_model = Model('marketing_activity');
        $map = array(
            'marketing_activity.marketing_activity_id' => $marketing_activity_id
        );
        $activity_info  = $marketing_activity_model->getOneData($map);
        echo isset($activity_info['marketing_activity_desc_html']) ? html_entity_decode($activity_info['marketing_activity_desc_html']) : '';
        die();
    }


    /**
     * 用户中心右边，小导航
     *
     * @param string    $menu_type  导航类型
     * @param string    $menu_key   当前导航的menu_key
     * @return
     */
    private function profile_menu($menu_key='') {
        Language::read('member_layout');
        $menu_array = array(
                1=>array('menu_key'=>'store_marketing_activity','menu_name'=>Language::get('nc_member_path_activity_list'),'menu_url'=>'index.php?act=store_marketing_activity&op=store_marketing_activity'),
                2=>array('menu_key'=>'activity_apply','menu_name'=>Language::get('nc_member_path_join_activity'),'menu_url'=>'')
        );
        if($menu_key == 'store_marketing_activity') {
            unset($menu_array[2]);
        }
        Tpl::output('member_menu',$menu_array);
        Tpl::output('menu_key',$menu_key);
    }
}
